package com.ljy.my_study.io.BIO.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/** 
* @author James
* @date 2018年11月5日 
*/
public class Server {
	ServerSocket serverSocket;

	private Set<Socket> sockets=new HashSet<>();
	private Map<Socket,PrintWriter> socketMap=new HashMap<>();
	
	public Server(ServerSocket serverSocket) {
		this.serverSocket=serverSocket;
	}
	
	public static void main(String[] args) throws IOException {
		Server server=new Server(new ServerSocket(2333));
		while(true) {
			Socket socket=server.serverSocket.accept();
			server.sockets.add(socket);
			new Thread(new Runnable() {
				@Override
				public void run() {
					BufferedReader in=null;
					PrintWriter out=null;
					try {
						in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
						out=new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true);
						server.socketMap.put(socket,out);
						String line;
						while(true) {
							line=in.readLine();
							if(line!=null) {
								System.out.println(line);
//								out.println(line);
								for(Entry<Socket,PrintWriter> e:server.socketMap.entrySet()) {
									String s=null;
									if(e.getKey()==socket)s="(自己)";
									else s="(其他人)";
									e.getValue().println(s+line);
								}
							}
						}
					} catch (IOException e) {
						e.printStackTrace();
					}finally {
						if(in!=null) {
							try {
								in.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
						if(out!=null) {
							out.close();
						}
					}
				}
			}).start();
		}
	}
	
	
}
